//
//  MainViewController.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2023/12/19.
//

import UIKit

class MainViewController: BasicNavibarVC {
    
    var superSnapshotView:UIView? //上一级窗口截屏，用做镜头动画
    var superSnapshotPosition:CGPoint? //镜头动画定位
    
    public var didCloseBlock:((_ snapshot:UIImage?)->Void)? //os_block_t? 关闭时回传当前view的截图，以便首页进行破碎动画
    
    let tableView:UITableView = {
        let table = UITableView()
        return table
    }()
    
    var sectionData:[String] = []
    var dataSource:[[TQQListModel]] = []
    var iTableLoadSection:Int = 0 //因为要动态生成列表，记录当前生成的section个数
    
//    deinit {
//        print("没有循环引用才会触发:MainViewController.deinit")
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //会因为navigationController，而使systemBackground在暗黑模式下并不是黑色，而=black则是黑色
        // Do any additional setup after loading the view.
        if let snapView = superSnapshotView{
            snapView.frame = CGRect(x: 0, y: 0, width: screen_W, height: screen_H)
            self.view.addSubview(snapView)
        }
        self.rightBar.title = "COLOR"
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let _ = superSnapshotView, let position = superSnapshotPosition{
            self.view.animateCircular(withDuration: 0.5, center: position) {[weak self] in
                self?.superSnapshotView?.removeFromSuperview()
                self?.superSnapshotView = nil
            }
        }
    }
    
    override func clickRightbarItem(){
        let nextVC = SubViewController()
        nextVC.title = "System Color"
        self.navigationController?.pushViewController(nextVC, animated: true)
        
        //usingSpringWithDamping传入数值为0.0~1.0,数值越大,弹性越不明显
        //initialSpringVelocity数值越大，初始速度越大
//        UIView.animate(withDuration: 0.5, delay:0.25, usingSpringWithDamping: 0.25, initialSpringVelocity: 9.8, options: [.curveEaseIn]) {
//            sender.frame = CGRect(x: 30, y: 900, width: 100, height: 44)
//        }
        
//        if let theSnapshot = SwiftFunc.captureScreen2Image(){
//            if let rect = self?.view.bounds{
//                let imageView = UIImageView(frame: CGRect(x: 0, y: 300, width: rect.width, height: rect.height-300))
//                self?.view.addSubview(imageView)
//                imageView.image = theSnapshot
//            }
//        }
    }

    override func initView(){
        if self.navigationController != nil{
//            self.navigationController?.navigationBar.backgroundColor = .yellow //设置所有navi页面的bar的背景色(不包括时钟栏背景,整体会很丑)
//            self.navigationController?.navigationBar.barTintColor = .green //无效
//            self.navigationController?.navigationBar.isTranslucent = false //不显示半透明背景(实际没啥关系，用systemGreen就会有半透明效果,用green就不会有半透明)
            
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .systemGreen //设置navigationBar的背景色(包含时钟栏背景)
            self.navigationController?.navigationBar.standardAppearance = appearance;
            self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance
            
            let leftBar = UIBarButtonItem(title: "注销", style:.done, target: self, action: #selector(closeVC))
            self.navigationItem.setLeftBarButton(leftBar, animated: true) //显示本页面标题栏左按钮
            
            self.navigationItem.backButtonTitle = "返回" //修改push出来的下级页面，返回按钮的title由默认的back，改为"返回"
        }
//        let sectionData:[String] = ["UILabel","UIButton","tableView","Dialog","ScrollView","仿头条标题栏","Tabbar","菜单"]
        
//        let titleData:[[String]] = [["阴影&渐变文字","文字走马灯","闪烁文字","标签云","","快播标签","打印机特效"],
//                                    ["图文","动画"],
//                                    ["变长table"],
//                                    ["Dialog"],
//                                    ["ScrollView"],
//                                    ["仿头条标题栏"],
//                                    ["Tabbar"],
//                                    ["菜单"]]
//        let vcList:[[String]] = [["GradientLabelVC"]]
        self.sectionData.append("UILabel")
        let arr_label:[TQQListModel] = [TQQListModel.init(title: "阴影&渐变&跑马灯&闪显闪隐", targetVC: "GradientLabelVC"),
                                        TQQListModel.init(title: "云标签&快播标签", targetVC: "CloudTagLabelVC"),
                                        TQQListModel.init(title: "球形滚动标签", targetVC: "BollTagLabelVC"),
                                        TQQListModel.init(title: "打印机特效", targetVC: "TyperwriteLabelVC")
                                    ]
        var labelData:[TQQListModel] = []
        for i in 0 ..< arr_label.count{
           let model = arr_label[i]
            model.createAttributedString(i+1)
            labelData.append(model)
        }
        self.dataSource.append(labelData)
        
        
        self.sectionData.append("UIButton")
        let arr_btn:[TQQListModel] = [TQQListModel.init(title: "图文按钮", targetVC: "ImageButtonVC"),
                                      TQQListModel.init(title: "自定义圆角&虚线框按钮", targetVC: "CornerButtonVC"),
                                        TQQListModel.init(title: "特效按钮", targetVC: "AnimateButtonVC")
                                    ]
        var btnData:[TQQListModel] = []
        for i in 0 ..< arr_btn.count{
           let model = arr_btn[i]
            model.createAttributedString(i+1)
            btnData.append(model)
        }
        self.dataSource.append(btnData)
        
        
        self.workView.addSubview(tableView)
        tableView.frame = workView.bounds
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 50
//        tableView.sectionHeaderHeight = 24 //无效
        tableView.separatorStyle = .none //默认即为singleLine(有分隔线)
//        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "normalTableCell")
//        tableView.backgroundColor = .clear //默认是systemBackground
    
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25){[weak self] in
            if let self = self{
//2种方法动态生成列表数据显示
////1.生成section(insertSections时table会自动生成该section对应的cell,故insertSections后不要再insertRows)
                for i in 0 ..< self.sectionData.count{
                    self.iTableLoadSection = i+1
                    self.tableView.insertSections([i], with: .top)
                }
//2.如果是单个section时，则需要insertRows生成cells
//                for i in 0 ..< self.sectionData.count{
//                    var indexPaths:[IndexPath] = []
//                    for j in 0 ..< self.dataSource[i].count{
//                        indexPaths.append(IndexPath(item: j, section: i))
//                    }
//                    self.tableView.insertRows(at: indexPaths, with: .fade)
//                }
                
            }
        }
        
        
    }
    
    @objc func closeVC(){
        Vibrations.light.vibrate()
//        if let theSnapshot = self.view.snapshot2Image(){ //这种只会将整个View截屏转成图片，而navigationbar不包含在内，需要对整个屏幕截屏转成image
        if let theSnapshot = SwiftFunc.captureScreen2Image(){
            self.didCloseBlock?(theSnapshot)
        }
        self.dismiss(animated: false)
    }

}


extension MainViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return iTableLoadSection
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if iTableLoadSection>0{
            return dataSource[section].count
        }else{
            return 0
        }
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 20 //无效
//    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if iTableLoadSection>0{
            return sectionData[section]
        }else{
            return nil
        }
    }

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = TQQListTableCell.createTableViewCellWithTableView(tableView: tableView)
        cell.updateContent(modelInfo: dataSource[indexPath.section][indexPath.row], at: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section >= dataSource.count || indexPath.row >= dataSource[indexPath.section].count{
            return
        }
        let tqqModel = self.dataSource[indexPath.section][indexPath.row]
        if let clsName = tqqModel.targetVC{
            if let cls = SwiftFunc.getClassFromString(clsName) as? UIViewController.Type {
                let destVC = cls.init()
                destVC.title = tqqModel.title
                self.navigationController?.pushViewController(destVC, animated: true)
            }
        }
        
    }
    
}
